/**************************************************************************//**
 * @file     sys_core.h
 * @brief    系统接口
 * @version  V0.0.1
 * @date     2020-02-01
 ******************************************************************************/
/*
 * Copyright (c) 2004, 2005 by xiao xiang. All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software
 * is freely granted, provided that this notice is preserved.
 */
#include "common.h"
#include "log_api.h"
#include "sys_api.h"
#include "stm32f1xx.h"
#include "hal_stm32f1xx_rcc_api.h"

#include "sys_core.h"

uint32_t g_SysTick = 0;         // SYSTICK, 以毫秒为单位
uint32_t g_enRstTypeMask = 0;   // 复位原因

// 系统滴答定时器（也就是周期性溢出的时基定时器）
void SysTick_Handler(void)
{
    g_SysTick++;
    return;
}

// 获取系统TICK
uint32_t SYS_SysTickGet(void)
{
    return g_SysTick;
}

// 延时函数，单位ms
void SYS_DelayMs(uint32_t delay)
{
    uint32_t endTick = g_SysTick + delay;    
    
    while (g_SysTick <= endTick);

    return;
}

// 获取系统复位原因
uint32_t SYS_ResetTypeInit(void)
{
    UN_RCC_CSR unCsr;
    
    unCsr.reg = RCC->CSR.reg;

    if (unCsr.PINRSTF == 1) {
        g_enRstTypeMask |= SYS_RST_TYPE_PIN;
    }

    if (unCsr.PORRSTF == 1) {
        g_enRstTypeMask |= SYS_RST_TYPE_POR;
    }

    if (unCsr.SFTRSTF == 1) {
        g_enRstTypeMask |= SYS_RST_TYPE_SOFT;
    }

    if (unCsr.IWDGRSTF == 1) {
        g_enRstTypeMask |= SYS_RST_TYPE_IWDG;
    }

    if (unCsr.WWDGRSTF == 1) {
        g_enRstTypeMask |= SYS_RST_TYPE_WWDG;
    }

    if (unCsr.LPWRRSTF == 1) {
        g_enRstTypeMask |= SYS_RST_TYPE_LPWR;
    }

    LOG_INFO("Reset Type = %x\r\n", g_enRstTypeMask);

    // 最后清除复位原因
    RCC->CSR.RMVF = 1;

    return RET_OK;
}

// 获取系统复位原因
uint32_t SYS_ResetTypeGet(void)
{
    return g_enRstTypeMask;
}